<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"/>
        <span>筛选搜索</span>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="queryInfo" size="small" label-width="140px">
          <el-form-item label="人脉圈标题：">
            <el-input style="width: 300px" v-model="queryInfo.title" placeholder="请输入人脉圈标题"></el-input>
          </el-form-item>
          <el-form-item label="人脉圈类型：">
            <el-select style="width: 300px" v-model="queryInfo.type" placeholder="请选择人脉圈类型">
              <el-option
                v-for="item in networkTypes"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button
            style="float: right"
            type="primary"
            size="medium"
            icon="el-icon-search"
            @click="getDataList()"
          >
            搜索
          </el-button>
          <el-button
            style="float: right;margin-right: 15px"
            size="medium"
            @click="handleResetSearch()"
          >
            重置
          </el-button>
        </el-form>

      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"/>
      <span>人脉圈列表</span>
      <el-button
        class="btn-add"
        size="medium"
        type="primary"
        style="float: right;margin-bottom: 15px"
        icon="el-icon-plus"
        @click="showDialog(0, 'add')"
      >
        添加
      </el-button>
    </el-card>
    <div class="table-container">
      <el-table
        ref="tableList"
        v-loading="listLoading"
        :data="datalist"
        border
        stripe
      >
        <el-table-column type="index" width="60" align="center"/>
        <el-table-column label="标题" align="center">
          <template slot-scope="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="类型" width="" align="center">
          <template slot-scope="scope">{{ scope.row.type }}</template>
        </el-table-column>
        <el-table-column label="话题" align="center">
          <template slot-scope="scope">{{ scope.row.topic }}</template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <p>
              <el-button
                size="mini"
                type="warning"
                @click="handleEditPage(scope.row.id)"> 管理
                <!--                @click="showDialog(scope.row.id, 'edit')"> 管理-->
              </el-button>
              <el-button
                size="mini"
                type="danger"
                @click="removeDataById(scope.row.id)"> 删除
              </el-button>
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes,prev, pager, next,jumper"
        :page-size="queryInfo.pageSize"
        :page-sizes="[5,10,15]"
        :current-page.sync="queryInfo.pageNum"
        :total="queryInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%" @close="dialogClosed"
               :close-on-press-escap="false" :close-on-click-modal="false">
      <!-- 步骤条 -->
      <el-steps :active="active" finish-status="success">
        <el-step title="第一步：基本信息"></el-step>
        <el-step title="第二步：选择好友"></el-step>
        <el-step title="第三步：创建完成"></el-step>
      </el-steps>

      <!-- 1. 人脉圈基本信息 -->
      <el-form
        v-show="active===0"
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :disabled="type === 'show'"
        label-width="100px">
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form-item label="标题" prop="title">
              <el-input v-model="formData.title" placeholder="请输入人脉圈标题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form-item label="类型" prop="type">
              <el-input v-model="formData.type" placeholder="请输入人脉圈类型" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center">
          <el-col :span="20">
            <el-form-item label="话题" prop="topic">
              <el-input v-model="formData.topic" placeholder="请输入人脉圈话题" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row type="flex" justify="center">-->
<!--          <el-col :span="20">-->
<!--            <el-form-item label="是否公开">-->
<!--              <el-switch-->
<!--                v-model="formData.visible"-->
<!--                active-color="#13ce66">-->
<!--              </el-switch>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
      </el-form>

      <!-- 2. 选择添加好友 -->
      <div v-show="active===1" align="center">
        <div align="center">
          <el-card class="friend-card" align="center" :style="{width: '60%'}" shadow="hover">
            <div align="center">
              <div :style="{width: '100%'}">
                <p :style="{width: '15%', float: 'left'}">昵称：</p>
                <el-input v-model="friendsQueryInfo.nickName" placeholder="请输入" size="small" clearable
                          :style="{width: '58%', float: 'left'}">
                </el-input>
                <el-button icon="el-icon-search" type="primary" size="small" @click="getFriendsList()"
                           :style="{marginLeft: '1px', float: 'left'}" round>查询
                </el-button>
              </div>
            </div>
            <div align="center">
              <el-table
                max-height="400px"
                ref="friendList"
                v-loading="friendsListLoading"
                :data="friends"
                style="width: 100%"
                @selection-change="handleSelectionChange">
                >
                <el-table-column
                  type="selection"
                  width="55">
                </el-table-column>
                <el-table-column label="选择好友" align="left">
                  <template slot-scope="scope">
                    <el-row type="flex" justify="start" align="top">
                      <el-col :span="5">
                        <el-avatar size="medium" :src="scope.row.avatar"></el-avatar>
                      </el-col>
                      <el-col :span="19">
                        <div class="text-nickName" align="start">{{ scope.row.nickName }}</div>
                        <div class="text-brief" align="start">{{ scope.row.signature }}</div>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </div>
<!--            <div class="pagination-container" align="center">-->
<!--              <el-pagination-->
<!--                :style="{width: '100%'}"-->
<!--                background-->
<!--                layout="prev, pager, next"-->
<!--                :page-size="friendsQueryInfo.pageSize"-->
<!--                :current-page.sync="friendsQueryInfo.pageNum"-->
<!--                :total="friendsQueryInfo.total"-->
<!--                @size-change="handleChooseSizeChange"-->
<!--                @current-change="handleChooseCurrentChange"-->
<!--              />-->
<!--            </div>-->
          </el-card>
        </div>
      </div>

      <!-- 弹框：底部操作信息 -->
      <div slot="footer" align="center">
        <el-button style="margin-top: 12px;" @click="stepBefore" :disabled="active===0">上一步</el-button>
        <el-button style="margin-top: 12px;" v-if="active===0" @click="stepNext">下一步</el-button>
        <el-button v-show="active===1" type="primary" @click="addNetworkUsers"> 完成</el-button>
        <el-button @click="dialogVisible = false"> 取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  insertNetworkInfo,
  deleteNetwork,
  getNetworkTypes,
  pageNetwork,
  editNetworkInfo,
  insertNetworkUsers
} from '@/api/network'
import request from "@/utils/request";
import {mapGetters} from "vuex";

export default {
  computed: {
    ...mapGetters([
      'name',
      'id',
      'user'
    ])
  },
  data() {
    return {
      // 步骤条激活
      active: 0,
      // 好友列表
      friends: [],
      //好友查询条件
      friendsQueryInfo: {
        id: '',
        nickName: '',
        account: '',
        total: 0,
        pageNum: 1,
        pageSize: 5
      },
      // 人脉圈类型
      networkTypes: [],
      // 添加成功后返回人脉圈信息
      network: {},
      // 弹出框类型
      type: '',
      // 获取用户列表查询参数对象
      queryInfo: {
        userId: '',
        title: '',
        type: '',
        // 当前页数
        pageNum: 1,
        // 每页显示多少数据
        pageSize: 5,
        total: 0
      },
      multipleSelection: [],
      datalist: [],
      listLoading: false,
      friendsListLoading: false,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新建人脉圈',
      // 添加修改人脉圈表单
      formData: {
        id: '',
        title: '',
        type: '',
        topic: '',
        visible: 0
      },
      // 用户添加表单验证规则
      formRules: {
        title: [
          {required: true, message: '请输入人脉圈标题', trigger: 'blur'},
          {min: 1, max: 20, message: '标题的长度在1～20个字', trigger: 'blur'}
        ],
        type: [
          {required: true, message: '请输入人脉圈类型', trigger: 'blur'},
          {
            min: 1,
            max: 10,
            message: '类型的长度在1～10个字',
            trigger: 'blur'
          }
        ],
        topic: [
          {required: true, message: '请输入人脉圈话题', trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.getDataList()
    this.getNetworkTypes()
  },
  methods: {
    getDataList() {
      this.listLoading = true
      // 传入当前登录用户id
      this.queryInfo.userId = this.user.id
      const params = this.queryInfo
      pageNetwork(params).then(response => {
        this.datalist = response.data.records
        this.queryInfo.pageNum = response.data.current
        this.queryInfo.pageSize = response.data.size
        this.queryInfo.total = response.data.total
        this.listLoading = false
        this.listLoading = false
      })
    },
    getFriendsList() {
      //  传入当前登录用户id
      this.friendsQueryInfo.id = this.user.id
      const params = this.friendsQueryInfo
      request({
        url: '/friend/getFriends',
        method: 'get',
        params
      }).then(response => {
        this.friends = response.data
        // this.friendsQueryInfo.total = response.data.total
        this.friendsListLoading = false
      })
    },

    // 获得所选的好友信息
    handleSelectionChange(val) {
      // TODO 下一页后数据丢失
      this.multipleSelection = val
    },

    handleChooseSizeChange(newSize) {
      this.friendsQueryInfo.pageSize = newSize
      this.getFriendsList()
    },

    handleChooseCurrentChange(newSize) {
      this.friendsQueryInfo.pageNum = newSize
      this.getFriendsList()
    },
    // 搜索人脉圈类型下选框
    getNetworkTypes() {
      getNetworkTypes().then(res => {
        this.networkTypes = res.data;
      })
    },
    handleResetSearch() {
      this.queryInfo = {
        pageNum: 1,
        pageSize: 5
      }
    },
    submitForm(networkId) {
      if (networkId === undefined) {
        console.log("添加人脉圈基本信息")
        this.addNetworkInfo()
        // 添加基本信息后，步骤条进入第二页 --> 选择好友
      } else {
        console.log("修改人脉圈基本信息")
        this.editNetworkInfo(networkId)
      }
      if (this.active++ > 1) this.active = 1

    },
    // 添加人脉圈基本信息
    addNetworkInfo() {
      // 提交请求前，表单预验证
      this.$refs.formRef.validate(async valid => {
        // 表单预校验失败
        if (!valid) return
        this.formData.visible = this.formData.visible === true ? 1 : 0
        // 新增时当前登录用户为管理员
        this.formData.userId = this.user.id
        const params = this.formData
        insertNetworkInfo(params).then(response => {
          if (response.retCode === '200') {
            // this.$message.success('添加人脉圈成功！')
            this.network = response.data
          }
        }).catch(() => {
          this.$message.error('添加人脉圈失败！')
        })
      })
    },
    editNetworkInfo(networkId) {
      // 提交请求前，表单预验证
      this.$refs.formRef.validate(async valid => {
        // 表单预校验失败
        if (!valid) return
        this.formData.visible = this.formData.visible === true ? 1 : 0
        // 新增时当前登录用户为管理员
        this.formData.userId = this.user.id
        this.formData.id = networkId
        const params = this.formData
        editNetworkInfo(params).then(response => {
          if (response.retCode === '200') {
            this.$message.success('修改人脉圈基本信息成功！')
            this.formData.visible = this.network.visible === 1
          }
        }).catch(() => {
          this.$message.error('修改人脉圈基本信息失败！')
        })
      })
    },
    // 跳转页面-修改人脉圈基本信息
    handleEditPage(id) {
      this.$router.push({
        path: '/network/setting',
        // name: '人脉圈设置',
        query: {
          networkId: id
        }
      })
    },

    // 添加人脉圈完成
    addNetworkUsers() {
      let friendIds = this.multipleSelection.map(item => item.id)
      // 当前用户id
      console.log("当前登录用户id", this.user.id)
      let userId = this.user.id
      let networkId = this.network.id
      let params = {networkId, userId, friendIds}
      insertNetworkUsers(params).then(res => {
        if (res.retCode === '200') {
          this.$message.success("人脉圈添加成员成功")
        }
      })
      this.dialogClosed()
    },
    // 删除
    async removeDataById(id) {
      const confirmResult = await this.$confirm(
        '此操作将删除该人脉圈及其成员, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 点击确定 返回值为：confirm
      // 点击取消 返回值为： cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      deleteNetwork(id).then(response => {
        // if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
        this.$message.success('删除用户成功！')
        this.getDataList()
      })
    },
    // 显示对话框
    showDialog(id, str) {
      this.dialogVisible = true
      this.getFriendsList()
    },
    // 监听 添加用户对话框的关闭事件
    dialogClosed() {
      this.$refs.formRef.resetFields()
      this.active = 0
      this.dialogVisible = false
      this.multipleSelection = []
    },
    // 步骤条上一步
    stepBefore() {
      if (this.active-- < 1) this.active = 0;
      this.formData.visible = this.network.visible === 1
    },
    // 步骤条下一步
    stepNext() {
      // 点击下一步添加/修改人脉圈基本信息
      // 提交请求前，表单预验证
      this.$refs.formRef.validate(async valid => {
        // 表单预校验失败
        if (!valid) return
        console.log('this.network.id', this.network.id);
        if (this.network.id === undefined) {
          this.submitForm()
        } else {
          this.submitForm(this.network.id)
        }
      })
    },
    // 监听 pagesize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getDataList()
    },
    // 监听 页码值 改变事件
    handleCurrentChange(newSize) {
      this.queryInfo.pageNum = newSize
      this.getDataList()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
